package du.contact2018.data;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.text.TextUtils;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import du.contact2018.R;
import du.contact2018.database.SQLHelper;
import du.contact2018.database.SqlMethod;
import du.contact2018.model.Contant;
import du.contact2018.model.InfoBean;
import du.contact2018.model.TreeElement;

public class TreeDataProvider implements DataProvider {

    String TAG = getClass().getSimpleName();

    private Context context = null;
    private ArrayList<TreeElement> nodes = new ArrayList<>();

    //用于 保存xml解析后数据，之后保存到数据库中
    ArrayList<InfoBean> infoBeanList = new ArrayList<>();


    public TreeDataProvider(Context context) {
        super();
        this.context = context;
    }


    private Intent getIntent(Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(context, cls);
        return intent;
    }

    @Override
    public void foward(String caption) throws Exception {

    }


    @Override
    public ArrayList<TreeElement> getDataSource() {
        if (null == nodes || nodes.size() == 0)
            initDataSource();
        return nodes;
    }


    private void initDataSource() {
        //通过网络，读入 电话xml格式文件
        new MyAsyncTask().execute(Contant.ContactURL.url);
    }


    class MyAsyncTask extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... strings) {
          
/*
网络下载有问题，超时

            // 网络okhttp下载 xml
            String url = strings[0];

            //1.创建OkHttpClient对象
            OkHttpClient okHttpClient = new OkHttpClient();


            //2.创建Request对象，设置一个url地址,设置请求方式。
            Request request = new Request.Builder()
                    .url(url)
                    .get()//默认就是GET请求，可以不写
                    .build();

            //3.创建一个call对象,参数就是Request请求对象
            Call call = okHttpClient.newCall(request);
            call.timeout().timeout(10,TimeUnit.SECONDS);

            //4.请求加入调度,重写回调方法
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "onFailure: ------------------" + call.toString());
                }

                @Override
                public void onResponse(Call call, Response response)   {
                    try {
                        //拿到字节流
                        InputStream inputStream = response.body().byteStream();

                        //解析xml
                        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
                        SAXParser saxParser = saxParserFactory.newSAXParser();
                        SAXParserHandler saxParserHandler = new SAXParserHandler();
                        saxParser.parse(inputStream, saxParserHandler);

                        inputStream.close();
                        System.out.println("-------------http------finish-------------" );


                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    } catch (ParserConfigurationException e) {
                        e.printStackTrace();
                    } catch (SAXException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            });
            
*/


            //
            //
            //
            //
            //
            //


            //从raw获取xml
            try {
                InputStream inputStream = context.getResources().openRawResource(R.raw.tel2018);

                //解析xml
                SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
                SAXParser saxParser = saxParserFactory.newSAXParser();
                SAXParserHandler saxParserHandler = new SAXParserHandler();
                saxParser.parse(inputStream, saxParserHandler);

                inputStream.close();
                System.out.println("-------------raw------finish-------------" + infoBeanList.size());

            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            // TODO: 2018/12/30 写入数据库 
            writeToDatabase();

            // TODO: 2018/12/30 启动界面 

        }
    }

    private void writeToDatabase() {
        // TODO: 2018/12/30  


        SqlMethod sqlMethod = new SqlMethod(context);

        sqlMethod.saveInfoBeans(infoBeanList);

    }


    //  : 2018/12/29
    class SAXParserHandler extends DefaultHandler {

        String[] bumenStrings = new String[]{
                "校长", "德育", "教务", "总务", "办公", "会计", "文印", "教师",
                "初中", "语文", "数学", "英语", "外语", "理化", "物理", "化学", "生物", "综合",
                "小学", "体育", "微机", "阅览", "图书", "校医", "食堂", "后勤", "门卫"};

        InfoBean infoBean = null;
        boolean isNotData = false;
        boolean isNotContactWorksheet = false;
        int curIndex = -1;
        HashMap<Integer, String> mapTemp = new HashMap<>();
        String unitName = "";//保存单位名称，读取工作表标签，格式：“兆丰学校通讯录”
        String deptName = "";//保存部门名称


        @Override
        public void startDocument() throws SAXException {
            super.startDocument();
        }

        @Override
        public void endDocument() throws SAXException {
            super.endDocument();
        }


        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

            // 读到 通讯录 工作表
            if ("Worksheet".equals(qName)) {

                String attributeName = attributes.getValue("Name");

                if (attributeName.contains("通讯录")) {
                    unitName = attributeName.replace("通讯录", "");
                    isNotContactWorksheet = false;
                } else {
                    unitName = "";
                    isNotContactWorksheet = true;
                }

            }

            //如不是 通讯录 工作表，跳过
            if (isNotContactWorksheet) {
                return;
            }

            //开始新行
            if ("Row".equals(qName)) {
                mapTemp = new HashMap<>();
                curIndex = -1;
            }

            if ("Cell".equals(qName)) {
                curIndex++;

                //如果Cell有Index属性，则需要修正curIndex
                if (!TextUtils.isEmpty(attributes.getValue("Index"))) {
                    curIndex = Integer.valueOf(attributes.getValue("Index")) - 1;
                }
            }

            if ("Data".equals(qName)) {
                isNotData = false;
            } else {
                isNotData = true;
            }


        }


        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {

            if (isNotContactWorksheet) {
                return;
            }

            if (!"Row".equals(qName))
                return;

            //删除中间之空格
            String name = mapTemp.get(0).replace(" ", "");


            // 是台头行
            if ("姓名".equals(name))
                return;

            infoBean = new InfoBean();

            //如果是“部门”名称，不是人员的姓名
            for (int i = 0; i < bumenStrings.length; i++) {
                if (null != name) {
                    if (name.contains(bumenStrings[i])) {
                        infoBean.setUnit(unitName);
                        infoBean.setDept(name);
                        infoBeanList.add(infoBean);
                        deptName = name;//保存部门名称
                        return;
                    }
                }
            }

            //构建Bean开始
            //人员姓名
            infoBean.setName(name);
            infoBean.setUnit(unitName);
            infoBean.setDept(deptName);


            //办公室电话可能是多个，之间空格隔开
            if (null != mapTemp.get(1)) {
                String[] split = mapTemp.get(1).trim().split(" ");
                for (int i = 0; i < split.length; i++) {
                    if (!TextUtils.isEmpty(split[i]))
                        infoBean.getOfficePhones().add(split[i]);
                }
            }

            //宅电可能是多个，之间空格隔开
            if (null != mapTemp.get(2)) {
                String[] split = mapTemp.get(2).trim().split(" ");
                for (int i = 0; i < split.length; i++) {
                    if (!TextUtils.isEmpty(split[i]))
                        infoBean.getHomePhones().add(split[i]);
                }
            }

            //手机可能是多个，之间空格隔开
            if (null != mapTemp.get(3)) {
                String[] split = mapTemp.get(3).trim().split(" ");
                for (int i = 0; i < split.length; i++) {
                    if (!TextUtils.isEmpty(split[i]))
                        infoBean.getMobilePhones().add(split[i]);
                }
            }

            infoBeanList.add(infoBean);

        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {

            if (isNotContactWorksheet) {
                return;
            }

            if (isNotData) {
                return;
            }

            String valueString = String.valueOf(ch, start, length);
            if (mapTemp.get(curIndex) == null) {
                mapTemp.put(curIndex, valueString);
            } else {
                mapTemp.put(curIndex, mapTemp.get(curIndex) + " " + valueString);
            }

        }
    }

}
